package br.com.sigeden.dao;

import br.com.sigeden.model.Autor;
import br.com.sigeden.util.HibernateUtil;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author David Amom <davidamom@gmail.com>
 */
public class AutorDAO {

    private Session sessao;
    private Transaction transacao;
    private List<Autor> envolvidos;

    public List<Autor> listarAutores() {
        sessao = HibernateUtil.getSessionFactory().openSession();

        Criteria criteria = sessao.createCriteria(Autor.class);
        this.envolvidos = criteria.list();

        sessao.close();
        return envolvidos;
    }

    public void adicionarAutor(Autor autor) {
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();

            Autor a = new Autor();
            a.setNome(autor.getNome());
            a.setEmail(autor.getEmail());
            a.setTelefone(autor.getTelefone());
            a.setSexo(autor.getSexo());

            sessao.save(a);
            transacao.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sessao.close();
        }
    }

    public void removerAutor(Autor autor) {
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();

            sessao.delete(autor);
            transacao.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sessao.close();
        }
    }

    public void atualizarAutor(Autor autor) {
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();

            sessao.update(autor);
            transacao.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sessao.close();
        }
    }
}
